package com.example.remoteassistance;

import android.content.Context;
import android.content.Intent;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.litepal.LitePal;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "LoginActivity";

    private EditText mUsername;
    private EditText mPassword;
    private Button mLogin;
    private Button mRegister;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //初始化界面
        initViews();
    }

    @Override
    protected void onStart() {
        super.onStart();
        //从SP读取用户名
        mUsername.setText(SPUtils.get(mContext, "username", "").toString());
        if (!mUsername.getText().toString().trim().equals("")) {
            mPassword.requestFocus();
        }
    }

    //初始化界面
    private void initViews() {
        mContext = getApplicationContext();
        mUsername = (EditText) findViewById(R.id.et_login_username);
        mPassword = (EditText) findViewById(R.id.et_login_password);
        mLogin = (Button) findViewById(R.id.bt_login_login);
        mRegister = (Button) findViewById(R.id.bt_login_register);
        mLogin.setOnClickListener(this);
        mRegister.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //点击登录按钮
            case R.id.bt_login_login:
                login();
                break;
            //点击注册按钮
            case R.id.bt_login_register:
                startActivity(new Intent(this, RegisterActivity.class));
                finish();
                break;
        }
    }

    //判断用户名和密码输入是否规范
    private boolean isLoginEditValid(String username, String password) {
        if (username.equals("")) {
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
            return false;
        } else if (password.equals("")) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    //登录
    private void login() {
        final String url = URLUtils.HTTPURL + "login";
        String username = mUsername.getText().toString().trim();
        String password = mPassword.getText().toString().trim();

        //判断用户名和密码是否规范
        if (isLoginEditValid(username, password)) {
            //密码MD5加密
            String passwordMD5 = MD5Utils.getMD5(password);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        String data = "username=" + URLEncoder.encode(username, "UTF-8")
                                + "&password=" + URLEncoder.encode(passwordMD5, "UTF-8");

                        //HTTP POST数据
                        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                        conn.setRequestMethod("POST");
                        conn.setReadTimeout(3000);
                        conn.setConnectTimeout(3000);
                        conn.setUseCaches(false);

                        OutputStream out = conn.getOutputStream();
                        out.write(data.getBytes());
                        out.flush();
                        out.close();

                        //判断应答 接收回传数据
                        if (conn.getResponseCode() == 200) {
                            InputStream in = conn.getInputStream();
                            ByteArrayOutputStream msg = new ByteArrayOutputStream();
                            int len = 0;
                            byte buf[] = new byte[1024];
                            while ((len = in.read(buf)) != -1) {
                                msg.write(buf, 0, len);
                            }
                            in.close();
                            msg.close();

                            //判断登录状态
                            String loginType = msg.toString();
                            switch (loginType) {
                                //登录成功
                                case "SUCCESS":
                                    //用户名传入SP
                                    SPUtils.put(mContext, "username", username);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            //跳转到主界面
                                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                            intent.putExtra("mid", username);
                                            startActivity(intent);
                                            Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
                                            finish();
                                        }
                                    });
                                    break;
                                //登录失败
                                case "FAIL":
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(LoginActivity.this, "登陆失败", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    break;
                                //用户已登录
                                case "ONLINE":
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(LoginActivity.this, "用户已登陆", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    break;
                                //用户未注册
                                case "UNREGISTERED":
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(LoginActivity.this, "用户未注册", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    break;
                                //密码错误
                                case "PASSWORDERROR":
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    break;
                            }
                        }
                    } catch (SocketTimeoutException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "服务器连接超时", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}